import React, {
  useEffect,
  useState,
  useImperativeHandle,
  forwardRef
} from 'react'
import { loadPieceComponentPack } from '@/apis/piece'
import type { PieceComponentPack } from '@/types/piece'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger
} from '@/components/ui/tooltip'

interface PieceComponentPackListProps {
  onSelect?: (pack: PieceComponentPack) => void
}

export interface PieceComponentPackListRef {
  refresh: () => void
}

const PieceComponentPackList = forwardRef<
  PieceComponentPackListRef,
  PieceComponentPackListProps
>(({ onSelect }, ref) => {
  const [packs, setPacks] = useState<PieceComponentPack[]>([])
  const [loading, setLoading] = useState(false)
  const [hovered, setHovered] = useState(false)
  const [selectedId, setSelectedId] = useState<number | null>(null)

  const loadData = async () => {
    setLoading(true)
    try {
      const data = await loadPieceComponentPack()
      setPacks(data)
    } catch (error) {
      console.error('Failed to load piece component packs:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadData()
  }, [])

  useImperativeHandle(
    ref,
    () => ({
      refresh: loadData
    }),
    []
  )

  return (
    <div
      className="group fixed right-0 top-1/2 z-50 -translate-y-1/2"
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        minWidth: hovered ? 260 : 40,
        transition: 'all 0.3s cubic-bezier(.4,2,.6,1)'
      }}
    >
      <div className="overflow-hidden rounded-l-2xl border border-slate-200 bg-white shadow-2xl transition-all duration-300 dark:border-neutral-700 dark:bg-neutral-900">
        {/* 标题栏 */}
        <div className="flex items-center gap-2 border-b border-slate-100 bg-gradient-to-r from-slate-50 to-white px-3 py-2 dark:border-neutral-800 dark:from-neutral-900 dark:to-neutral-800">
          <svg
            className="size-4 text-blue-400"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
            />
          </svg>
          <span className="select-none text-base font-bold tracking-wide text-slate-700 dark:text-neutral-200">
            分享列表
          </span>
        </div>
        {loading ? (
          <div className="flex flex-col items-center justify-center p-6 text-slate-400">
            <svg
              className="mb-2 size-6 animate-spin text-blue-400"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                className="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
              ></circle>
              <path
                className="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8v8z"
              ></path>
            </svg>
            <span>加载中...</span>
          </div>
        ) : (
          <TooltipProvider>
            <ul className="max-h-[60vh] divide-y divide-slate-100 overflow-y-auto dark:divide-neutral-800">
              {packs.map((pack) => (
                <Tooltip key={pack.id}>
                  <TooltipTrigger asChild>
                    <li
                      className={[
                        'flex cursor-pointer items-center gap-2 p-3 rounded-lg mx-2 my-1 transition-all duration-200',
                        'hover:bg-blue-50 hover:shadow-md dark:hover:bg-neutral-800',
                        selectedId === pack.id
                          ? 'bg-blue-100 dark:bg-neutral-700 shadow-lg border border-blue-300 dark:border-blue-800'
                          : ''
                      ].join(' ')}
                      onClick={() => {
                        setSelectedId(pack.id)
                        onSelect?.(pack)
                      }}
                    >
                      <div className="min-w-0 flex-1">
                        <div className="truncate text-sm font-medium text-slate-700 dark:text-neutral-200">
                          {pack.title}
                        </div>
                        <div className="truncate text-xs text-slate-400 dark:text-neutral-500">
                          {pack.name}
                        </div>
                      </div>
                      <svg
                        className="size-4 text-slate-300 transition group-hover:text-blue-400"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          d="M9 5l7 7-7 7"
                        />
                      </svg>
                    </li>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>
                      分享时间:{' '}
                      {new Date(pack.updated_at).toLocaleString('zh-CN')}
                    </p>
                  </TooltipContent>
                </Tooltip>
              ))}
            </ul>
          </TooltipProvider>
        )}
      </div>
    </div>
  )
})

PieceComponentPackList.displayName = 'PieceComponentPackList'

export default PieceComponentPackList
